<?php
/*
 * Created on 2012-2-28
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
class QQAuth_Operation
{
	
	/**
	 * 获取授权函数
	 * 
	 * @param $direct_auth boolean 直接请求授权
	 * @param $redirect_uri string 授权成功后的回调地址
	 * @param $scope string 请求授权的项目，使用","分隔
	 * @param $auth_domain string 请求路径域名
	 * 
	 */ 
	public static function getAuth( $direct_auth = false, $redirect_uri = QQAUTH_REDIRECT_URI, $scope = QQAUTH_SCOPE, $auth_domain = QQAUTH_AUTH_DOMAIN )
	{
		$_SESSION['state'] = md5(uniqid(rand(), TRUE));
		// 请求参数
		$params = array(
						'response_type' => 'code',
						'client_id' 	=> QQAUTH_APP_ID,
						'redirect_uri' 	=> $redirect_uri,
						'scope' 		=> $scope ,
						'state'	 		=> $_SESSION['state']
					); 
		
		// 构造请求的url
		$url = $auth_domain . QQAuth_Util::composeParams($params);
		
		// 存储redirect uri， 以备下一步用
		$_SESSION['QQAUTH_REDIRECT_URI'] = $redirect_uri;
		
		// 请求方式
		if( $direct_auth )
		{ 
			header('Location: ' . $url);
		}
		else
		{
			return $url;
		}
	}
	
	/**
	 * 处理授权回调函数
	 * 
	 * @return $res_array array 授权码，令牌与openid组成的数组，开发者可以将其写入数据库。
	 * 
	 */ 
	public static function handleAuthCallback($access_token_uri = QQAUTH_ACCESS_TOKEN_DOMAIN, $openid_uri = QQAUTH_OPENID_DOMAIN)
	{
		if ($_SESSION['state'] !== $_REQUEST['state'])
		{
			throw new QQAuth_Exception('CSRF attacks!', '9999999');
		}
		
		if ( self::isAuth())
		{// 不是从验证服务器转来的请求
			return ;
		}
		$res_array = array();
		$code = isset( $_GET['code'] ) ? $_GET['code']: '';
		if( $code == '' )
		{
			throw new QQAuth_Exception('Auth failure!', '9999998');
		} 
		
		$res_array['auth_code'] = $_SESSION['QQAUTH_AUTHCODE'] = $code; 
		$state = 'test';
		
		$token_params = array(
							'grant_type' 	=> 'authorization_code',
							'client_id' 	=> QQAUTH_APP_ID,
							'client_secret'	=> QQAUTH_APP_KEY,
							'code'			=> $code,
							'state'			=> $state,
							'redirect_uri'	=> $_SESSION['QQAUTH_REDIRECT_URI']
						);
		
		$request_access_token_url = $access_token_uri . QQAuth_Util::composeParams($token_params);
		
		$response = QQAuth_Util::doGet($request_access_token_url);
		
		$msg = QQAuth_Util::parseJSONP( $response );

        if (isset($msg->error))
        {
            echo "<h3>error:</h3>" . $msg->error;
            echo "<h3>msg  :</h3>" . $msg->error_description;
            exit;
        }

        $params = array();
        parse_str($response, $params);

        //debug
        //print_r($params);

        //set access token to session
        $res_array['access_token'] = $_SESSION["QQAUTH_ACCESS_TOKEN"] = $params["access_token"];
        
        
        $graph_url = $openid_uri . 'access_token=' . $_SESSION['QQAUTH_ACCESS_TOKEN'];

	    $str  = QQAuth_Util::doGet( $graph_url );

	    $user = QQAuth_Util::parseJSONP( $str );
	    
	    if (isset($user->error))
	    {
	        echo "<h3>error:</h3>" . $user->error;
	        echo "<h3>msg  :</h3>" . $user->error_description;
	        exit;
	    }
		
		$res_array['openid'] = $_SESSION["QQAUTH_OPENID"] = $user->openid;
	    //debug
	    //echo("Hello " . $user->openid);
		return $res_array;
	}
	
	/**
	 * 判断是否通过远程服务器的验证
	 * 
	 * @return boolean 
	 * 如果通过则返回true
	 * 
	 */
	public static function isAuth()
	{
		if ( QQAuth_Util::allSet( $_SESSION["QQAUTH_ACCESS_TOKEN"], $_SESSION["QQAUTH_OPENID"]) )
		{
			return true;
		}
		return false;
	}
	
}
